/**
 * 
 */
package com.cqan.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cqan.exception.AppException;

/**
 * @Description 图片上传传用控制器 些控制器上传的文件可以直接通过URL访问文件，不做权限认证
 * @author slaton.wu@gmail.com
 * @date 2012-7-23下午3:56:04
 * 
 */
@Controller
@RequestMapping("/attach/pic")
public class PictureUploadController extends CommonUploadController {

	private String savepath = "attachment";

	@Override
	@ResponseBody
	@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
	public String upload(HttpServletRequest request) throws AppException {
		try {
			String id = StringUtils.defaultIfEmpty(request.getParameter("id"),String.valueOf(System.currentTimeMillis()));
			String uploader = request.getParameter("uploader");
			String token = request.getHeader("token");
			String uid = request.getHeader("uid");
			if (token!=null&&!"".equals(token)) {
				id = uid;
			}
			if (uploader != null) {
				savepath = uploader;
			}
			StringBuffer sb = new StringBuffer();
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile attachment = multipartRequest.getFile("attachment");
			if (attachment.isEmpty()) {
				throw new AppException("upload.file");
			}
			String fileName = attachment.getOriginalFilename();
			List<String> exts = Arrays.asList(allowedSuffix);
			String suffix = null;
			int li = fileName.lastIndexOf(".");
			if (li != -1) {
				suffix = fileName.substring(li, fileName.length());
			}
			if (suffix == null || !exts.contains(suffix.toLowerCase())) {
				throw new AppException("upload.suffix");
			}
			String path = request.getSession().getServletContext()
					.getRealPath("/");
			String saveFilePath = new StringBuffer().append(savepath)
					.append(createSavePath()).toString();
			File tempsaveFile = new File(path + saveFilePath);
			if (!tempsaveFile.exists()) {
				tempsaveFile.mkdirs();
			}
			String url = saveFilePath + id + suffix;
			File savefile = new File(path + url);
			savefile.deleteOnExit();
			FileCopyUtils.copy(attachment.getBytes(), savefile);
			sb.append(url);
			return sb.toString();

		} catch (IOException e) {
			e.printStackTrace();
			throw new AppException("upload.unknown");
		}
	}

}
